/****************************************************
     Author: Brian J Clifton
     Url: http://www.advanced-web-metrics.com
     This script is free to use as long as this info is left in
     
     DESCRIPTION: Script for tracking the first and last referrer of a visitor as detailed in Chapter 9 of the book
	Advanced Web Metrics with Google Analytics (second edition).
          
     All scripts presented have been tested and validated by the author and are believed to be correct
     as of the date of publication or posting. The Google Analytics software on which they depend is 
     subject to change, however; and therefore no warranty is expressed or implied that they will
     work as described in the future. Always check the most current Google Analytics documentation.

****************************************************/
// Last update Sep-2009

<script type="text/javascript">
   var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
   document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript"%3E%3C/script%3E"));

function _uGC(l,n,s) {
   // used to obtain a value form a string of key=value pairs
   if (!l || l=="" || !n || n=="" || !s || s=="") return "-";
   var i,i2,i3,c="-";
   i=l.indexOf(n);
   i3=n.indexOf("=")+1;
   if (i > -1) {
      i2=l.indexOf(s,i); if (i2 < 0) { i2=l.length; }
      c=l.substring((i+i3),i2);
   }
   return c;
}

function checkFirst(){
   // check if this is a first time visitor and if so, set flag
   newVisitor = 0;
   var myCookie = " " + document.cookie + ";";
   var searchName = "__utma=";
   var startOfCookie = myCookie.indexOf(searchName)
   if (startOfCookie == -1) {   // i.e. first time visitor
      newVisitor = 1;
   }
}

function grabReferrer(){
   // if first visit, grab utmz cookie values and put in utmv
   if (newVisitor) {
      var z = _uGC(document.cookie, "__utmz=", ";");
      urchin_source = _uGC(z,"utmcsr=", "|");
      urchin_medium = _uGC(z,"utmcmd=", "|");
      urchin_term = _uGC(z,"utmctr=", "|");
      urchin_content = _uGC(z,"utmcct=", "|");
      urchin_campaign = _uGC(z,"utmccn=", "|");
      var gclid = _uGC(z,"utmgclid=","|");
      if (gclid != "-")  {
		urchin_source.value = "google";
		urchin_medium.value = "cpc";
		urchin_term.value = "cpc";
		urchin_content.value = "cpc";
		urchin_campaign.value = "cpc";
      }
      if (urchin_term != "-"){
         urchin_term = urchin_term.replace(/%27/g, "'");      //decode
         urchin_term = urchin_term.replace(/%22/g, "'");      //decode
         urchin_term = urchin_term.replace(/\+/g, " ");       //decode
         urchin_term = urchin_term.replace(/%20/g, " ");      //decode
         pageTracker._setVar(urchin_term);
      }
   }
}
try{
   var pageTracker = _gat._getTracker("UA-12345-1");
   checkFirst();
   pageTracker._trackPageview();
   grabReferrer();
}catch(err) {}</script>
